//保留两位小数
export const toDecimal2 = x => {
  var f = parseFloat(x);
  if (isNaN(f)) {
      return '0.00';
  }
  var f = Math.round(x * 100) / 100;
  var s = f.toString();
  var rs = s.indexOf('.');
  if (rs < 0) {
      rs = s.length;
      s += '.';
  }
  while (s.length <= rs + 2) {
      s += '0';
  }
  return s;
}

export const formatPhone =(phone) => {
  if (!phone) return ''
  return phone.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
}

export const computedImgSize = (e) => {
  var imageSize = {};
  var originalWidth = e.width;//图片原始宽
  var originalHeight = e.height;//图片原始高
  var originalScale = originalHeight / originalWidth;//图片高宽比

  console.log('原始宽: ' + originalWidth)
  console.log('原始高: ' + originalHeight)
  console.log('宽高比' + originalScale)
  //获取屏幕宽高
  wx.getSystemInfo({
    success: function (res) {
      // canvas 基础宽高调为 2 倍，避免图片压缩程度过高导致图片字体显示不清楚
      var windowWidth = res.windowWidth * 2;
      var windowHeight = res.windowHeight * 2;
      var windowscale = windowHeight / windowWidth;//屏幕高宽比

      // 图片尺寸大于设备
      if (originalWidth > res.windowWidth || originalHeight > res.windowHeight) {
        if (originalScale < windowscale) {//图片高宽比小于屏幕高宽比
          //图片缩放后的宽为屏幕宽
          imageSize.imageWidth = windowWidth;
          imageSize.imageHeight = (windowWidth * originalHeight) / originalWidth;
        } else {//图片高宽比大于屏幕高宽比
          //图片缩放后的高为屏幕高
          imageSize.imageHeight = windowHeight;
          imageSize.imageWidth = (windowHeight * originalWidth) / originalHeight;
        }
      } else {
        imageSize.imageHeight = originalHeight;
        imageSize.imageWidth = originalWidth;
      }
    }
  })
  console.log('缩放后的宽: ' + imageSize.imageWidth)
  console.log('缩放后的高: ' + imageSize.imageHeight)
  return imageSize;
}

// 去除空格,type: 1-所有空格 2-前后空格 3-前空格 4-后空格
export const trim = (str, type) => {
  type = type || 1
  switch (type) {
      case 1:
          return str.replace(/\s+/g, "");
      case 2:
          return str.replace(/(^\s*)|(\s*$)/g, "");
      case 3:
          return str.replace(/(^\s*)/g, "");
      case 4:
          return str.replace(/(\s*$)/g, "");
      default:
          return str;
  }
}

export const zip = (...arrays) => {
  const maxLength = Math.max(...arrays.map(x => x.length));
  return Array.from({ length: maxLength }).map((_, i) => {
    return Array.from({ length: arrays.length }, (_, k) => arrays[k][i]);
  });
};

export const zipWith = (...array) => {
  const fn =
    typeof array[array.length - 1] === 'function' ? array.pop() : undefined;
  return Array.from({ length: Math.max(...array.map(a => a.length)) }, (_, i) =>
    fn ? fn(...array.map(a => a[i])) : array.map(a => a[i])
  );
};
